﻿using Common;
using Http;
using Log4_Net;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        //IOC 
        private IHost _host;

        public static IHostBuilder CreateHostBuilder() => new HostBuilder().ConfigureAppConfiguration((context, configurationBuilder) =>
        {
            configurationBuilder.AddEnvironmentVariables();
            configurationBuilder.SetBasePath(context.HostingEnvironment.ContentRootPath);

            var appsetting = "appsettings.json";
#if DEBUG
appsetting = "appsettings.Development.json";
#endif
            configurationBuilder.Add(new JsonConfigurationSource { Path = appsetting, ReloadOnChange = true })
               .Build();
 
        });
        public App()
        {
            _host= CreateHostBuilder().ConfigureServices((context, services) =>
            {
                 
                Singleton<IConfiguration>.Instance = services.GetConfiguration();
                services.AddLog4Net();
                services.AddHttpClients();
                services.AddSingleton<MainWindow>();
            }).Build();

        }
         
        private async void Application_Startup(object sender, StartupEventArgs e)
        {

            await _host.StartAsync();

            var mainWindow = _host.Services.GetService<MainWindow>();
            mainWindow.Show();

        }

        private  void Application_Exit(object sender, ExitEventArgs e)
        {
            _host.Services.GetRequiredService<MainWindow>().Close();

            var frame = new DispatcherFrame(false);

             Task.Run(async () => {
                try
                {
                    await _host.StopAsync();
                }
                finally
                {
                    frame.Continue = false;
                }
            });

            Dispatcher.PushFrame(frame);

            _host.Dispose();

            _host = null;
        }
    }
}
